//
//  Extensions.swift
//  TradingPlatform
//
//  Created by tam on 2017/8/8.
//  Copyright © 2017年 Wilkinson. All rights reserved.
//

import UIKit

extension UIColor {

    //自定义16进制颜色
    class func R_UIColorFromRGB(color:Int) -> UIColor {
        return UIColor(red: ((CGFloat)((color & 0xFF0000) >> 16)) / 255.0,
                       green: ((CGFloat)((color & 0xFF00) >> 8)) / 255.0,
                       blue: ((CGFloat)(color & 0xFF)) / 255.0,
                       alpha: 1.0)
    }
}

extension UIImage {

    //使用颜色创造图片
    class func creatImageWithColor(color: UIColor, size: CGSize, alpha: CGFloat) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let content = UIGraphicsGetCurrentContext()
        content?.setFillColor(color.cgColor)
        content?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!;
    }
    
    //重设图片大小
    func resizeImage(resultSize: CGSize ) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(resultSize, false, UIScreen.main.scale)
        self.draw(in: CGRect.init(x: 0, y: 0, width: resultSize.width, height: resultSize.height))
        let resizeImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!.withRenderingMode(.alwaysOriginal)
        UIGraphicsEndImageContext()
        return resizeImage
    }
    
    //等比例缩放
    func scaleImage(scaleSize: CGFloat) -> UIImage {
        let reSize = CGSize.init(width: self.size.width * scaleSize, height: self.size.height * scaleSize)
        return resizeImage(resultSize: reSize)
    }
    
    func resizeImageWithcornerRadius() -> UIImage {
        
        let rect = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()
        context?.addEllipse(in: rect)
        context?.clip()
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        return newImage!
    }
}

extension UIButton {
    
    class func setBtnBoarderCorner(radius:CGFloat) -> UIButton {
        let btn = UIButton()
        btn.clipsToBounds = (radius != 0 );
        btn.layer.cornerRadius = radius;
        return btn
    }
    
}

extension UIView {
    
     func setViewBoarderCorner(radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.masksToBounds = true
    }
    
    //设置渐变色
    func setGradualColor(startColor:UIColor, endColor: UIColor) {
        
        let gradientLayer = CAGradientLayer.init()
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
        gradientLayer.locations = [0.5,1.0]
        gradientLayer.startPoint = CGPoint.init(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint.init(x: 1.0, y: 0)
        gradientLayer.frame = self.frame
        self.layer.addSublayer(gradientLayer)
    }
    
}

extension UserDefaults {
    
    func saveCustomObject(customObject object: NSCoding, key: String) {
        let encodedObject = NSKeyedArchiver.archivedData(withRootObject: object)
        self.set(encodedObject, forKey: key)
        self.synchronize()
    }
    
    func getCustomObject(forKey key: String) -> AnyObject? {
        let decodedObject = self.value(forKey: key) as? Data
        
        if let decoded = decodedObject {
            let object = NSKeyedUnarchiver.unarchiveObject(with: decoded)
            return object as AnyObject
        }
        
        return nil
    }
}

extension String {
    
    func md5() -> String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
//        return String(format: hash as String).uppercased()
        return String(format: hash as String)
    }
    
}

extension UILabel {
    
    func getStringSize(text:String ,size:CGSize,font:CGFloat) -> CGSize{
        var newSize = CGSize();
        let attributes = [NSFontAttributeName : UIFont.systemFont(ofSize: font)]
        newSize = text.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes  , context: nil).size;
        return newSize
    }
}

//MARK: 
public protocol BackBarButtonItemDelegate {
    func viewControllerShouldPopOnBackBarButtonItem() -> Bool
}

extension UINavigationController {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPopItem _: UINavigationItem) -> Bool {
        if viewControllers.count < (navigationBar.items?.count)! {
            return true
        }
        var shouldPop = true
        if let viewController = topViewController as? BackBarButtonItemDelegate {
            shouldPop = viewController.viewControllerShouldPopOnBackBarButtonItem()
        }
        if shouldPop {
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        } else {
            // Prevent the back button from staying in an disabled state
            for view in navigationBar.subviews {
                if view.alpha < 1.0 {
                    UIView.animate(withDuration: 0.25, animations: { () in
                        view.alpha = 1.0
                    })
                }
            }
        }
        return false
    }
}



extension UINavigationBar {
    
    private struct AssociatedKeys {
        static var NAV_BAR_KEY = "NavigationBarcoverView"
    }
    
    func hideBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(self)
        navigationBarImageView?.isHidden = true
    }
    
    func showBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(self)
        navigationBarImageView?.isHidden = false
    }
    
    fileprivate func hairlineImageViewInNavigationBar(_ view: UIView) -> UIImageView? {
        if view.isKind(of: UIImageView.self) && view.bounds.height <= 1.0 {
            return (view as? UIImageView)
        }
        
        let subviews = (view.subviews as [UIView])
        for subview: UIView in subviews {
            if let imageView = hairlineImageViewInNavigationBar(subview) {
                return imageView
            }
        }
        
        return nil
    }
    
    /// 定义的一个计算属性，如果可以我更希望直接顶一个存储属性。它用来返回和设置我们需要加到
    /// UINavigationBar上的View
    var coverView: UIView? {
        get {
            // 这句的意思大概可以理解为利用key在self中取出对应的对象,如果没有key对应的对象就返回niu
            return objc_getAssociatedObject(self, &AssociatedKeys.NAV_BAR_KEY) as? UIView
        }
        
        set {
            // 与上面对应是重新设置这个对象，最后一个参数如果学过oc的话很好理解，就是代表这个newValue的属性
            // OBJC_ASSOCIATION_RETAIN_NONATOMIC意味着:strong,nonatomic
            objc_setAssociatedObject(self, &AssociatedKeys.NAV_BAR_KEY, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    // 在透明导航栏需要渐变时使用
    func setMyBackgroundColor(_ color: UIColor, alpha: CGFloat = 0) {
        if let coverView = self.coverView {
            coverView.backgroundColor = color
        } else {
            setBackgroundImage(UIImage(), for: .default)
            shadowImage = UIImage()
            
            let view = UIView(frame: CGRect(x: 0, y: -20, width: UIScreen.main.bounds.size.width, height: bounds.height + 20))
            view.isUserInteractionEnabled = false
            view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
            insertSubview(view, at: 0)
            
            view.backgroundColor = color
            coverView = view
        }
        titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white.withAlphaComponent(alpha)]
    }
    
    func setMyBackgroundColorAlpha(_ alpha: CGFloat) {
        if let coverView = coverView {
            coverView.backgroundColor = coverView.backgroundColor?.withAlphaComponent(alpha)
        }
    }
}

extension CALayer {
    func shake() {
        let keyFrameAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        let s = 16
        keyFrameAnimation.values = [0, -s, 0, s, 0, -s, 0, s, 0]
        keyFrameAnimation.duration = 0.1
        keyFrameAnimation.repeatCount = 2
        add(keyFrameAnimation, forKey: "shake")
    }
}

extension UIDevice {
    
    public func isX() -> Bool {
        if UIScreen.main.bounds.height == 812 {
            return true
        }
        return false
    }
    
    public func is5() -> Bool {
        if UIScreen.main.bounds.width == 320 {
            return true
        }
        return false
    }
    
}

extension UIView {
    
    func viewController() -> UIViewController {
        
        var next:UIResponder?
        next = self.next
        repeat {
            if (next?.isKind(of: UIViewController.self))! {
                return (next as! UIViewController)
            }else {
                next = next?.next
            }
        } while next != nil
        return UIViewController()
    }
    
}

